package Presentacion;

import Clases.Empleado;
import Clases.Vacacion;
import Clases.VacacionId;
import Clases.VacacionPagada;
import Control.ControlEmpleado;
import Control.ControlPago;
import Control.ControlVacaciones;
import Control.ControlVacacionesPagadas;
import de.javasoft.plaf.synthetica.SyntheticaLookAndFeel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class AsignarVacaciones extends javax.swing.JFrame {

    ControlEmpleado controlE = ControlEmpleado.obtenerInstancia();
    ControlVacaciones controlV = ControlVacaciones.obtenerInstancia();
    ControlVacacionesPagadas controlVP = ControlVacacionesPagadas.obtenerInstancia();
    ControlPago controlP = ControlPago.obtenerInstancia();
    DateFormat diaDomingo = new SimpleDateFormat("EEE");
    private ImageIcon iconoError;

    public AsignarVacaciones() {
        initComponents();
        inicioTooltops();
    }

    private void ocultarLabels() {
        labelFecha.setVisible(false);
        labelTotalVacaciones.setVisible(false);

    }

    private void inicioTooltops() {
        iconoError = new ImageIcon(getClass().getResource("/Imagenes/warning.png"));

        labelFecha.setIcon(iconoError);
        labelFecha.setToolTipText("Seleccione una fecha igual al día de hoy o posterior y no puede ser Domingo.");

        labelTotalVacaciones.setIcon(iconoError);
        labelTotalVacaciones.setToolTipText("No le quedan vacaciones restantes");

        ocultarLabels();
    }
    private static AsignarVacaciones instancia = null;

    public static AsignarVacaciones obtenerInstancia() {
        if (instancia == null) {
            instancia = new AsignarVacaciones();
        }
        return instancia;
    }

    public void init(String cedula, String nombre) {
        setTitle(" Asignación de Vacaciones");
        setLocationRelativeTo(null);
        UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
        SwingUtilities.updateComponentTreeUI(this);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        try {
            UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
            SyntheticaLookAndFeel.setWindowsDecorated(false);
            UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaAluOxideLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);

        } catch (Exception ex) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        this.setVisible(true);
        limpiar();
        this.setjLabelsEmpleado(cedula, nombre);
        ocultarLabels();

    }

    public void limpiar() {
        labelCedula.setText("________________");
        labelNombre.setText("________________");
        labelVacaciones.setText("________________");
        labelCodigo.setText("________________");
        DateVacacion.setCalendar(null);
        ocultarLabels();
    }

    public void setjLabelsEmpleado(String cedulaEmpleado, String nombre) {

        this.labelCedula.setText(cedulaEmpleado);
        this.labelNombre.setText(nombre);
        Empleado e = controlE.getEmpleadoCedula(Long.parseLong(cedulaEmpleado));
        this.labelVacaciones.setText(String.valueOf(calcularVacaciones(e.getFechaInicio(), e.getNumEmpleado())));
        this.labelCodigo.setText(String.valueOf(e.getCodigo()));

    }

    public void setjTextField2(String vacaciones) {

        this.labelVacaciones.setText(vacaciones);

    }

    boolean validarVacacion() {

        boolean itsK = true;

        if ("sunday".contains(diaDomingo.format(DateVacacion.getDate())) || "domingo".contains(diaDomingo.format(DateVacacion.getDate())) || DateVacacion.getDate() == null) {
            labelFecha.setVisible(true);
            itsK = false;
        }
        if (Integer.parseInt(labelVacaciones.getText()) <= 0) {
            labelTotalVacaciones.setVisible(true);
            itsK = false;
        }
        return itsK;
    }

    int calcularVacaciones(Date inicio, Long numEmpleado) {
        Date actual = new Date();
        int totalVacaciones = 0;
        int anioInicio = inicio.getYear();
        int anioActual = actual.getYear();
        int diaInicio = inicio.getDate();
        int diaActual = actual.getDate();
        int mesActual = actual.getMonth();
        int mesInicio = inicio.getMonth();
        if (anioInicio < anioActual) {
            mesInicio = 0;
            if (diaInicio <= diaActual) {
                mesInicio = 0;
                totalVacaciones = mesActual - mesInicio;
            } else if (diaInicio > diaActual) {

                totalVacaciones = mesActual - mesInicio - 1;

            }
        } else if (anioInicio == anioActual) {
            if (mesInicio == mesActual) {
                totalVacaciones = 0;
            } else if (mesInicio <= mesActual) {
                if (diaInicio > diaActual) {
                    totalVacaciones = mesActual - mesInicio - 1;
                } else if (diaInicio <= diaActual) {
                    totalVacaciones = mesActual - mesInicio;
                }

            }
        } else {
            JOptionPane.showMessageDialog(null, "La fecha inicio mator a la fecha actual", "Mensaje", JOptionPane.ERROR_MESSAGE);
        }
        List<Vacacion> vacaciones = controlV.getVacacionesPorNumEmpleado(numEmpleado);

        List<VacacionPagada> vacacionesP = controlVP.getVacacionesPorNumEmpleado(numEmpleado);

        if (!vacaciones.isEmpty()) {
            totalVacaciones = totalVacaciones - vacaciones.size();
        }
        if (!vacacionesP.isEmpty()) {
            totalVacaciones = totalVacaciones - vacacionesP.size();
        }

        return totalVacaciones;
    }
void ingresar(){
ocultarLabels();
        boolean error = validarVacacion();
        if (error == true) {
            Long cedula = Long.valueOf(labelCedula.getText());
            Date dateVacacion = DateVacacion.getDate();
            Date fechaHoy = new Date();
            Long numEmpleado = controlE.getEmpleadoCedula(cedula).getNumEmpleado();
            Empleado empleado = controlE.getEmpleadoCedula(cedula);
            VacacionId v = new VacacionId(dateVacacion, numEmpleado);
            Vacacion v2 = new Vacacion(v, empleado);
            if (dateVacacion == null) {
                labelFecha.setVisible(true);
            } else if (dateVacacion.compareTo(fechaHoy) >= 0) {
                boolean inserto = controlV.insertarVacaciones(v2);
                if (!inserto) {
                    JOptionPane.showMessageDialog(null, "No se pudo insertar la vacación", "Mensaje", JOptionPane.ERROR_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(null, "Vacacion ingresada con éxito", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                    ManejoVacaciones vacacion=ManejoVacaciones.obtenerInstancia();
                    vacacion.llenarTablaVacaciones(Integer.valueOf(labelVacaciones.getText())-1);
                    dispose();
                }
            } else {
                labelFecha.setVisible(true);
            }
        }

}
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        DateVacacion = new com.toedter.calendar.JDateChooser();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        labelFecha = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        labelTotalVacaciones = new javax.swing.JLabel();
        labelCedula = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        labelNombre = new javax.swing.JLabel();
        labelVacaciones = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        labelCodigo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(500, 280));
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("Asignar Vacaciones");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Cédula de empleado: ");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel3.setText("Día a asignar:");

        DateVacacion.setDateFormatString("dd-MM-yyyy");
        DateVacacion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                DateVacacionKeyPressed(evt);
            }
        });

        jButton2.setText("Asignar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Salir");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        labelFecha.setText("x");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel4.setText("Vacaciones Restantes:");

        labelTotalVacaciones.setText("x");
        labelTotalVacaciones.setMaximumSize(new java.awt.Dimension(24, 24));
        labelTotalVacaciones.setMinimumSize(new java.awt.Dimension(22, 22));

        labelCedula.setText("________________");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel5.setText("Nombre de empleado:");

        labelNombre.setText("_________________");

        labelVacaciones.setText("_________________");

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel6.setText("Código de empleado:");

        labelCodigo.setText("________________");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(0, 262, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(62, 62, 62))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(DateVacacion, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(labelFecha)
                .addGap(121, 121, 121))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(100, 100, 100)
                        .addComponent(jLabel1))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(labelVacaciones, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(16, 16, 16))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel5))
                                .addGap(24, 24, 24)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(labelCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(labelCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(labelNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addComponent(labelTotalVacaciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel6)))
                .addContainerGap(156, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(labelCedula))
                .addGap(18, 18, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(labelCodigo))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(labelNombre))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(labelVacaciones)
                    .addComponent(labelTotalVacaciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(DateVacacion, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton2)
                            .addComponent(jButton3)))
                    .addComponent(labelFecha))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.ingresar();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void DateVacacionKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_DateVacacionKeyPressed
        int key = evt.getKeyCode();
        if (key == evt.VK_ENTER) {
            this.ingresar();
        }
    }//GEN-LAST:event_DateVacacionKeyPressed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AsignarVacaciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AsignarVacaciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AsignarVacaciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AsignarVacaciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AsignarVacaciones().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.toedter.calendar.JDateChooser DateVacacion;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel labelCedula;
    private javax.swing.JLabel labelCodigo;
    private javax.swing.JLabel labelFecha;
    private javax.swing.JLabel labelNombre;
    private javax.swing.JLabel labelTotalVacaciones;
    private javax.swing.JLabel labelVacaciones;
    // End of variables declaration//GEN-END:variables
}
